package com.cms.controllers.admin;

import com.cms.common.config.LoginKeys;
import com.cms.common.model.entity.AdminUser;
import com.cms.common.model.services.AdminUserService;
import com.cms.common.model.vo.ResponseResult;
import com.cms.controllers.BaseController;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpSession;

@Controller
@RequestMapping("/admin/login")
public class LoginController extends BaseController {
    @Autowired
    AdminUserService adminUserService;

    @GetMapping("")
    public String index() {

        boolean isLogin = adminUserService.checkLogin(request, response);
        if (!isLogin) {
            return "admin/login";
        }
        return "redirect:/admin/dashboard";
    }

    @PostMapping("/act")
    @ResponseBody
    public ResponseResult login(@RequestParam("username") String username, @RequestParam("password") String password, @RequestParam(value = "remember", defaultValue = "false") boolean remember) {

        AdminUser adminUser = adminUserService.getAdminUserByUsername(username);
        if (adminUser == null) {
            return ResponseResult.fail("用户名或密码不正确");

        }
        if (!adminUser.getPassword().equals(adminUserService.encodePwd(username, password, adminUser.getSalt()))) {
            return ResponseResult.fail("用户名或密码不正确");
        }
        String cookieToken = adminUserService.token(adminUser.getUuid());
        String token = adminUserService.loginToken(adminUser.getUuid(), cookieToken);

        HttpSession session = request.getSession();
        session.setAttribute(LoginKeys.loginSessionKey, token);
        session.setAttribute(token, adminUser);

        Cookie cookie = new Cookie(LoginKeys.rememberLoginCookieKey, adminUser.getUuid() + "|" + cookieToken);
        // 保存7天
        cookie.setMaxAge(3600 * 24 * 7);
        response.addCookie(cookie);

        return ResponseResult.success("登录成功");
    }
}
